package com.limao.CacheManager;

import com.Hazelcast.Cache;
import com.Hazelcast.CacheFactory;
import com.limao.DBDataClass.UserOffLineDataClass;
import com.limao.DBProvider.UserOfflineProvider;
import com.limao.Tool.CacheClass;
import com.limao.cache.BasicModule;

public class user_offline_CacheManager  extends BasicModule{


	private UserOfflineProvider provider;
	private static user_offline_CacheManager instance;

    public static user_offline_CacheManager getInstance() {
        return instance;
    }
    
    private Cache<String, UserOffLineDataClass> user_offlineManagerCache;
 
 
    public user_offline_CacheManager() {
    	super("userAuthCacheManager");
    	user_offlineManagerCache = CacheFactory.createCache("cd_userOfflineManagerCache");
      	initProvider();
    }
    
    @Override
	public void initialize() {
        super.initialize();
        instance=this;
    }

    public void ClearObjectCache(String key)
    {
    	user_offlineManagerCache.remove(key);
    }   
    
    public UserOffLineDataClass load_User_Offline(int id, int type) {
        if ( id<1)     return null;
        
        UserOffLineDataClass obj = null;
        synchronized ((id+"_"+type).intern()) {
        	obj = user_offlineManagerCache.get(id+"_"+type);
            if (obj == null) {
            	obj = provider.load_User_Offline(id, type);
            	if(obj!=null)
            		user_offlineManagerCache.put(id+"_"+type, obj);
            }
        }
        return obj;
    }

    public void recordAppUsetime(int userid, int type, int onlined){
    	provider.recordAppUsetime(userid, type, onlined);
    }
    
    //onlined(1:登入 ,0:登出)
    public UserOffLineDataClass updateUserOffline(int id, int type, int onlined,String token)
    {
        if (id<1)      return null;
        
        UserOffLineDataClass obj =provider.updateUserOffline(id, type, onlined,token);
        if(obj!=null)
        	user_offlineManagerCache.put(id+"_"+type, obj);
        return obj;
    }
 
    public long getLastActivity(int id, int type) {
        long lastActivity = -1;
        UserOffLineDataClass obj= load_User_Offline(id, type);
        if(obj==null) return lastActivity;
        long offlineDate=CacheClass.getLongValue(obj.loginouttime);
        if(offlineDate<=0)
        	return lastActivity;
        lastActivity = (System.currentTimeMillis() - offlineDate);

        return lastActivity;
    }
    
    private void initProvider() {
        if (provider == null ) {
            try {
                provider =UserOfflineProvider.getInstance();
            }
            catch (Exception e) {
            	e.printStackTrace();
            }
        }
    }
  
}
